import os
import time
import logging

# 以浮点数形式返回CPU温度                                    
def  getCPUtemperature():
     file =  open("/sys/class/thermal/thermal_zone0/temp")
     temp = float(file.read()) / 1000
     file.close()
     return(temp)

# 在一个列表里返回内存信息                                      
# Index 0: 总内存                                                              
# Index 1: 已使用的内存                                                                
# Index 2: 剩余内存                                                                
def  getRAMinfo():
     p  = os.popen( 'free' )
     i  = 0
     while  1 :
         i  = i  + 1
         line  = p.readline()
         if  i == 2 :
             return (line.split()[ 1 : 4 ])
 
# 以字符串形式返回CPU使用率                               
def  getCPUuse():
     return ( str (os.popen( "top -n1 | awk '/Cpu\(s\):/ {print $2}'" ).readline().strip()))
 
# 以列表形式返回硬盘空间信息                    
# Index 0: 硬盘总容量                                                        
# Index 1: 已使用硬盘容量                                                        
# Index 2: 剩余硬盘容量                                                    
# Index 3: 硬盘使用率                                                 
def  getDiskSpace():
     p = os.popen( "df -h /" )
     i = 0
     while 1 :
         i  = i  + 1
         line  = p.readline()
         if i == 2 :
             return (line.split()[ 1 : 5 ])

# 获取设备所有信息
def get_info():
     
     # CPU信息
     CPU_temp  = getCPUtemperature()
     CPU_usage  = getCPUuse()
     
     # 内存信息
     # 是以kb为单位输出，这里换算成了Mb
     RAM_stats  = getRAMinfo()
     RAM_total  = round ( int (RAM_stats[ 0 ])  / 1024 , 1 )
     RAM_used  = round ( int (RAM_stats[ 1 ])  / 1024 , 1 )
     RAM_free  = round ( int (RAM_stats[ 2 ])  / 1024 , 1 )
     
     # 硬盘信息
     DISK_stats  = getDiskSpace()
     DISK_total  = DISK_stats[0]
     DISK_used  = DISK_stats[1]
     DISK_left = DISK_stats[2]
     DISK_perc  = DISK_stats[3]
     
     logging.info(
          "Local Time {timenow} \n"
          "CPU Temperature ={CPU_temp}'C \n"
          "CPU Use = {CPU_usage} %\n\n"
          "RAM Total = {RAM_total} MB\n"
          "RAM Used = {RAM_used} MB\n"
          "RAM Free = {RAM_free} MB\n\n"
          "DISK Total Space = {DISK_total}B\n"
          "DISK Used Space = {DISK_used}B\n"
          "DISK Left Space = {DISK_left}B\n"
          "DISK Used Percentage = {DISK_perc}\n"
          "".format(
               timenow = time.asctime(time.localtime(time.time())),
               CPU_temp = CPU_temp,
               CPU_usage = CPU_usage,
               RAM_total = str(RAM_total),
               RAM_used = str(RAM_used),
               RAM_free = str(RAM_free),
               DISK_total = str(DISK_total),
               DISK_used = str(DISK_used),
               DISK_left = str(DISK_left),
               DISK_perc = str(DISK_perc),
               )
     )

if __name__  == '__main__':
     # 获取信息
     logger_file = os.path.join('log_source_info.txt')
     handlers = [logging.FileHandler(logger_file, mode='w'), logging.StreamHandler()]
     logging.basicConfig(level=logging.INFO,handlers=handlers)
     
     # 循环
     # 检测退出后清除了缓存文件
     try:
          while(True):
               get_info()
               time.sleep(10)
               os.system('clear')
     except KeyboardInterrupt:
          print('Exiting......')
          os.system('rm -rf log_source_info.txt')
